package com.itlong.cloud.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.property.PropertyArrearPeopleSelectDTO;
import com.itlong.cloud.POJO.PO.DeviceBusinessChangeLogPO;
import com.itlong.cloud.POJO.PO.DeviceBusinessElevatorChangeLogPO;
import com.itlong.cloud.POJO.PO.DeviceBusinessEntranceChangeLogPO;
import com.itlong.cloud.POJO.PO.MomentRelievePO;
import com.itlong.cloud.POJO.VO.property.PropertyArrearPeopleSelectVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.CloudElevatorChangeBusinessEnum;
import com.itlong.cloud.enumerate.CloudEntranceChangeBusinessEnum;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.SmartCommunityEnum;
import com.itlong.cloud.property.dao.IPropertyArrearPeopleSelectDao;
import com.itlong.cloud.property.service.IPropertyArrearPeopleSelectService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *      欠费住户查询服务层接口实现类
 * </desc>
 *
 * @createDate 2019/05/21
 */
@Service
public class PropertyArrearPeopleSelectServiceImpl implements IPropertyArrearPeopleSelectService {

    @Autowired
    private IPropertyArrearPeopleSelectDao iPropertyArrearPeopleSelectDao;

    @Autowired
    private MessageSender messageSender;

    /**
     * <desc>
     *      分页获取欠费住户信息
     * </desc>
     *
     * @param propertyArrearPeopleSelectDTO 欠费住户信息DTO
     * @return 欠费住户分页信息
     * @author wangzhi
     * @createDate 2019/05/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<PropertyArrearPeopleSelectVO> getPage(PropertyArrearPeopleSelectDTO propertyArrearPeopleSelectDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(propertyArrearPeopleSelectDTO);
        Page<PropertyArrearPeopleSelectVO> page = new Page<>();
        page.getPage().setPageSize(propertyArrearPeopleSelectDTO.getPageSize());
        page.getPage().setCurrentPage(propertyArrearPeopleSelectDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        if (StringUtils.isNotBlank(propertyArrearPeopleSelectDTO.getArrearageMonth()) && StringHandlerUtil.strToIntDef(propertyArrearPeopleSelectDTO.getArrearageMonth(), -1) == -1) {
            page.setRows(new ArrayList<>(), 0);
            return page;
        }
        List<PropertyArrearPeopleSelectVO> propertyArrearPeopleSelectVOS = iPropertyArrearPeopleSelectDao.getPage(params);
        page.setRows(propertyArrearPeopleSelectVOS,iPropertyArrearPeopleSelectDao.getRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      临时解除限制
     * </desc>
     *
     * @param propertyArrearPeopleSelectDTO 欠费住户信息DTO
     * @return 受影响行数
     * @author wangzhi
     * @createDate 2019/05/22
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer momentRelieve(PropertyArrearPeopleSelectDTO propertyArrearPeopleSelectDTO) throws Exception {
        Date nowTime = new Date();
        MomentRelievePO momentRelievePO = new MomentRelievePO();
        momentRelievePO.setRoomId(propertyArrearPeopleSelectDTO.getRoomId());
        momentRelievePO.setUnitId(propertyArrearPeopleSelectDTO.getUnitId());
        momentRelievePO.setBuildId(propertyArrearPeopleSelectDTO.getBuildId());
        momentRelievePO.setProjectId(propertyArrearPeopleSelectDTO.getProjectId());
        momentRelievePO.setCreateUserId(propertyArrearPeopleSelectDTO.getLoginUserId());
        momentRelievePO.setOperateUserId(propertyArrearPeopleSelectDTO.getLoginUserId());
        momentRelievePO.setStatus(DataStatusEnum.NORMAL.getType());
        momentRelievePO.setCreateTime(nowTime);
        momentRelievePO.setUpdateTime(nowTime);
        Calendar calendar = Calendar.getInstance();
        // 获取该房间临时解除限制最大截止日期，满足大于当前日期
        String maxEndTime = iPropertyArrearPeopleSelectDao.getMaxEndTimeGreaterThanNow(propertyArrearPeopleSelectDTO.getRoomId());
        if (StringUtils.isNotBlank(maxEndTime)) {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
            Date maxEndTimeDate = sdf.parse(maxEndTime);
            calendar.setTime(maxEndTimeDate);
        }
        if ("0.5".equals(propertyArrearPeopleSelectDTO.getTime())) {
            calendar.add(Calendar.MINUTE, Integer.parseInt("30"));
        } else {
            calendar.add(Calendar.HOUR, Integer.parseInt(propertyArrearPeopleSelectDTO.getTime()));
        }
        momentRelievePO.setEndTime(calendar.getTime());
        iPropertyArrearPeopleSelectDao.deleteMomentRelieve(propertyArrearPeopleSelectDTO.getRoomId());
        Integer intRes = iPropertyArrearPeopleSelectDao.save(SqlUtil.durableData(momentRelievePO, PlatformConstants.TABLE_SAVE));
        // 更新房间欠费状态为不欠费状态
        iPropertyArrearPeopleSelectDao.updateRoomArrearageStatus0(propertyArrearPeopleSelectDTO.getRoomId());
        // 通过房间id查询房间下的住户
        List<String> userIdList = iPropertyArrearPeopleSelectDao.getUserIdsByRoomId(propertyArrearPeopleSelectDTO.getRoomId());
        for (String userId : userIdList) {
            // 判断用户项目下是否还有欠费房间，没有则更新用户项目为不欠费状态
            int arrearRoomCount = iPropertyArrearPeopleSelectDao.getArrearRoomCount(propertyArrearPeopleSelectDTO.getProjectId(), userId);
            if (arrearRoomCount == 0) {
                iPropertyArrearPeopleSelectDao.updateUserProjectArrearageStatus0(propertyArrearPeopleSelectDTO.getProjectId(), userId);
            } else {
                iPropertyArrearPeopleSelectDao.updateUserProjectArrearageStatus1(propertyArrearPeopleSelectDTO.getProjectId(), userId);
            }
        }

        List<DeviceBusinessChangeLogPO> changes = new ArrayList<>();
        List<DeviceBusinessElevatorChangeLogPO> elevatorChanges = new ArrayList<>();
        List<DeviceBusinessEntranceChangeLogPO> entranceChanges = new ArrayList<>();
        List<Map<String, Object>> roomList = new ArrayList<>();
        Map<String, Object> roomMap = new HashMap<>();
        roomMap.put("roomId", propertyArrearPeopleSelectDTO.getRoomId());
        roomList.add(roomMap);
        //推送房间更新消息
        DeviceBusinessChangeLogPO po = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_ROOM, JsonUtil.toJSON(roomList),
                propertyArrearPeopleSelectDTO.getProjectId());
        changes.add(po);
        DeviceBusinessElevatorChangeLogPO elevatorPo = new DeviceBusinessElevatorChangeLogPO(propertyArrearPeopleSelectDTO.getProjectId(),
                CloudElevatorChangeBusinessEnum.PUSH_ROOM_PWD, JsonUtil.toJSON(roomList));
        elevatorChanges.add(elevatorPo);
        DeviceBusinessEntranceChangeLogPO entrancePO = new DeviceBusinessEntranceChangeLogPO(propertyArrearPeopleSelectDTO.getProjectId(),
                CloudEntranceChangeBusinessEnum.PUSH_ROOM_PWD, JsonUtil.toJSON(roomList));
        entranceChanges.add(entrancePO);
        JSONObject dataJs = new JSONObject();
        dataJs.put("data", changes);
        //发送云对讲业务指令
        messageSender.send(
                RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                JsonUtil.toJSON(dataJs),
                RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);
        dataJs.put("data", elevatorChanges);
        //推送云电梯房间信息
        messageSender.send(
                RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ELEVATOR_CHANGE_BUSINESS_QUEUE,
                JsonUtil.toJSON(dataJs),
                RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_ROUTING_KEY);
        //发送云门禁指令
        dataJs.put("data", entranceChanges);
        messageSender.send(
                RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                JSON.toJSONString(dataJs),
                RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
        );
        return intRes;
    }

    /**
     * <desc>
     *      获取导出的欠费住户信息
     * </desc>
     *
     * @param propertyArrearPeopleSelectDTO 欠费住户信息DTO
     * @return 欠费住户列表信息
     * @author wangzhi
     * @createDate 2019/05/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<PropertyArrearPeopleSelectVO> getExportData(PropertyArrearPeopleSelectDTO propertyArrearPeopleSelectDTO) throws Exception {
        if (StringUtils.isBlank(propertyArrearPeopleSelectDTO.getFeeIds())) {
            if (StringUtils.isNotBlank(propertyArrearPeopleSelectDTO.getArrearageMonth()) && StringHandlerUtil.strToIntDef(propertyArrearPeopleSelectDTO.getArrearageMonth(), -1) == -1) {
                return new ArrayList<>();
            }
            Map<String,Object> params = SqlUtil.convertBeanToMapParams(propertyArrearPeopleSelectDTO);
            return iPropertyArrearPeopleSelectDao.getAllData(params);
        }
        List<String> feeIdList = StringHandlerUtil.splitStringList(propertyArrearPeopleSelectDTO.getFeeIds());
        return iPropertyArrearPeopleSelectDao.getDataByFeeIds(feeIdList, propertyArrearPeopleSelectDTO.getProjectId());
    }
}
